package com.nervenets.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.StaleObjectStateException;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class RetryOnOptiAspect {

	int maxRetries;

	@Pointcut("@annotation(com.nervenets.aspect.RetryOnOpti)")
	public void retryOnOpti() {
	}

	@Around("retryOnOpti()")
	public Object doAround(ProceedingJoinPoint pjp)
			throws Throwable {
		int numAttempts = 0;
		do {
			numAttempts++;
			try {
				
				return pjp.proceed();
			} catch (StaleObjectStateException ex) {
				System.err.println("===================================>RETRY");
				if (numAttempts > this.maxRetries) {
					// log failure information, and throw exception
					throw ex;
				} else {
					// log failure information for audit/reference
					// will try recovery
				}
			}
		} while (numAttempts <= this.maxRetries);

		return null;
	}
}
